import copy
import re
from urllib.parse import quote

import requests
from flask import json, jsonify, make_response, Blueprint

from exts import set_redis

regex = re.compile('/')

headers = {
    "Access-Control-Allow-Credentials": 'true',
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "X-Requested-With, accept, origin, content-type, x-access-token",
    "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                  '(KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36',
    'Host': 'www.zhuishushenqi.com',
    'Referer': 'http://www.zhuishushenqi.com',
}
chapter_headers = copy.deepcopy(headers)
del chapter_headers['Host']
del chapter_headers['Referer']


def get_search_content(query, start=1, limit=100):
    result = requests.get(
        'http://api.zhuishushenqi.com/book/fuzzy-search?query={}&start={}&limit={}'.format(query, start, limit),
        headers=headers)
    json_result = result.json()
    # line = json.dumps(json_result, ensure_ascii=False)
    return json_result


def get_book_info(book_id):
    result = requests.get(
        'http://api.zhuishushenqi.com/book/{}'.format(book_id),
        headers=headers)
    json_result = result.json()
    return json_result


def get_book_source(book_id):
    result = requests.get(
        'http://api.zhuishushenqi.com/atoc?view=summary&book={}'.format(book_id),
        headers=headers)
    result_list = json.loads(result.content)
    for i, val in enumerate(result_list):
        if val['name'] == "优质书源":
            del result_list[i]
            break
    return result_list


def get_chapter_by_book_id(book_id):
    result = requests.get(
        'http://api.zhuishushenqi.com/mix-atoc/{}?view=chapters'.format(book_id),
        headers=headers)
    json_result = result.json()
    return json_result


def get_chapter_by_source_id(source_id):
    result = requests.get(
        # 'http://api.zhuishushenqi.com/atoc/{}?view=chapters'.format(source_id),
        'http://api.zhuishushenqi.com/btoc/{}?view=chapters&channel=mweb'.format(source_id),
        headers=headers)
    json_result = result.json()
    return json_result


def encode_chapter_link(chapter_link):
    chapter_link = quote(chapter_link)
    chapter_link = regex.sub('%2F', chapter_link)
    return chapter_link


def get_book_chapter_content(chapter_link):
    # print(chapter_link)
    host = 'chapterup01.zhuishushenqi.com'
    chapter_headers['Host'] = host
    chapter_headers['Referer'] = 'http://' + host
    result = requests.get(
        'http://{}/chapter/{}'.format(host, chapter_link),
        # 'http://chapter2.zhuishushenqi.com/chapter/{}'.format(chapter_link),
        headers=chapter_headers)
    json_result = result.json()
    return json_result


def get_rank():
    result = requests.get(
        'http://api.zhuishushenqi.com/ranking/gender',
        headers=headers)
    json_result = result.json()
    return json_result


def get_rank_info(rank_id):
    result = requests.get(
        'http://api.zhuishushenqi.com/ranking/{}'.format(rank_id),
        headers=headers)
    print(result.url)
    json_result = result.json()
    return json_result


def get_sort_major_info():
    result = requests.get(
        'http://api.zhuishushenqi.com/cats/lv2/statistics',
        headers=headers)
    json_result = result.json()
    return json_result


def get_sort_all_info():
    result = requests.get(
        'http://api.zhuishushenqi.com/cats/lv2',
        headers=headers)
    json_result = result.json()
    return json_result


def get_sort_book(query):
    result = requests.get(
        'https://api.zhuishushenqi.com/book/by-categories',
        headers=headers, params=query)
    print(result.url)
    json_result = result.json()
    return json_result


def get_sort_more(more):
    result = requests.get(
        'https://api.zhuishushenqi.com/recommendPage/node/books/all/{}?ajax=ajax&size=10&st=1'.format(more),
        headers=headers)
    print(result.url)
    json_result = result.json()
    return json_result


def get_book_store(query):
    result = requests.get(
        'http://api.zhuishushenqi.com/v2/mweb/home',
        headers=headers, params=query)
    print(result.url)
    json_result = result.json()
    return json_result


def get_json_response(content, req, is_set_cache=True):
    status = content.get('ok', True)
    error_msg = content.get('error', None)
    if status is False:
        return server_exception(content['message'])
    if is_set_cache and error_msg is None:
        set_redis(req.full_path, content)
    response = make_response(jsonify(content))
    # print(content)
    # print(req)
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE,OPTIONS'
    response.headers[
        'Access-Control-Allow-Headers'] = 'X-Requested-With, accept, origin, content-type, x-access-token,Content-Type,Authorization,authorization,content-type'
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Cache-Control'] = 'no-cache'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Accept'] = 'application/json'
    return response


error = Blueprint('error', __name__)


@error.errorhandler(404)
def not_found(info=''):
    message = {
        'status': 404,
        'message': info,
    }
    resp = jsonify(message)
    resp.status_code = 404

    return resp


@error.errorhandler(500)
def server_exception(info=''):
    print(info)
    message = {
        'status': 500,
    }
    resp = jsonify(message)
    resp.status_code = 500

    return resp
